package com.wswy.wzcx.ui.car.result;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ItemDecoration;
import android.support.v7.widget.RecyclerView.State;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.AdModel;
import com.wswy.wzcx.model.MessageMode;
import com.wswy.wzcx.model.TrafficViolationInfo;
import com.wswy.wzcx.model.car.CarTypeData;
import com.wswy.wzcx.model.home.RPaths;
import com.wswy.wzcx.model.home.RouterUtils;
import com.wswy.wzcx.model.license.UserCarInfo;
import com.wswy.wzcx.model.resp.QueryResult;
import com.wswy.wzcx.module.InternalMsgCode;
import com.wswy.wzcx.module.base.CBaseActivity;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.Constants;
import com.wswy.wzcx.ui.activity.MineActivity;
import com.wswy.wzcx.ui.activity.MyServiceActivity;
import com.wswy.wzcx.ui.car.AddCarInfoActivity;
import com.wswy.wzcx.ui.car.choose.ChooseCarActivity;
import com.wswy.wzcx.ui.fragment.WyServiceFragment;
import com.wswy.wzcx.ui.message.MessageDetailFragment;
import com.wswy.wzcx.ui.other.ClickUtils;
import com.wswy.wzcx.utils.StringUtils;
import com.wswy.wzcx.utils.UiUtils;
import com.wswy.wzcx.utils.UnicornManager;
import com.wswy.wzcx.widget.NewbieGuideLayout;
import com.wswy.wzcx.widget.ResultHeadLayout;
import com.wswy.wzcx.widget.utils.VerticalCenterSpan;

import java.util.ArrayList;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;

public class QueryResultActivity extends CBaseActivity implements IQueryResultView, OnRefreshListener, OnClickListener {

    private static final String TAG = "QueryResultActivity";

    private static final int REQ_CHOOSE_CAR = 5;

    public static void start(Context context, UserCarInfo userCarInfo, int position) {
        Intent intent = new Intent(context, QueryResultActivity.class);
        intent.putExtra("carInfo", userCarInfo);
        intent.putExtra("position", position);
        context.startActivity(intent);
    }

    public static void start(Context context, int carId, int position) {
        UserCarInfo userCarInfo = new UserCarInfo();
        userCarInfo.id = carId;
        start(context, userCarInfo, position);
    }

    public static void start(Context context, QueryResult result, int position) {
        Intent intent = new Intent(context, QueryResultActivity.class);
        intent.putExtra("query.result", result);
        intent.putExtra("position", position);
        context.startActivity(intent);
    }


    private ViewGroup vgRootContent;

    private RecyclerView recyclerView;
    private TextView btnHelpPayment;

    private View layoutDataSuccess;
    private View layoutEmptyOrError;

    private View layoutBottomBtns;

    private TextView tvMsgContent;
    private TextView tvMsgTitle;
    private SimpleDraweeView imgIcon;
    private TextView btnNext;
    private TextView btnBack;

    private TextView tvFineHint;

    private ImageView customerImg;

    //  @BindView(R.id.shadow_view)
//  ShadowFrameLayout shadowView;
    private ResultHeadLayout headLayoutContent;

    private ViewGroup llSuccessAD;

    private NestedScrollView nestedScrollView;

    private QueryResultPresenter mPresenter;


    private SmartRefreshLayout smartRefreshLayout;
    private QueryLoadingHeader queryLoadingHeader;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_result);

        vgRootContent = findViewById(R.id.layout_root);
        recyclerView = findViewById(R.id.recycler_view);
        btnHelpPayment = findViewById(R.id.tv_help_pay);
        layoutDataSuccess = findViewById(R.id.layout_data_success);
        layoutEmptyOrError = findViewById(R.id.layout_empty_or_error);
        tvMsgContent = findViewById(R.id.tv_message_content);
        tvMsgTitle = findViewById(R.id.tv_message_title);
        imgIcon = findViewById(R.id.img_icon);
        btnNext = findViewById(R.id.btn_next);
        btnBack = findViewById(R.id.btn_back);
        headLayoutContent = findViewById(R.id.head_layout_content);
        llSuccessAD = findViewById(R.id.layout_success_ad);
        nestedScrollView = findViewById(R.id.nested_scrollview);
        customerImg = findViewById(R.id.img_query_result);
        customerImg.setOnClickListener(this);

        smartRefreshLayout = findViewById(R.id.refreshLayout);
        queryLoadingHeader = findViewById(R.id.query_header);
        layoutBottomBtns = findViewById(R.id.ll_btns);
        tvFineHint = layoutBottomBtns.findViewById(R.id.tv_fine_wzdb_hint);
        smartRefreshLayout.setOnRefreshListener(this);
        ResultTips.INSTANCE.reset();
        initClick();

        mPresenter = new QueryResultPresenter(this, this);
        showFineHint(0, 0, 0);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        final int dp67 = SizeUtils.dp2px(60);


//    final FineProgressBar progressBar = findViewById(R.id.progressBar);
//
//    Runnable runnable = new Runnable() {
//      @Override
//      public void run() {
//        progressBar.setProgress(80);
//        progressBar.postOnAnimation(this);
//      }
//    };
//
//    progressBar.postOnAnimation(runnable);

        recyclerView.addItemDecoration(new ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int position = parent.getChildAdapterPosition(view);
                if (position == state.getItemCount() - 1) {
                    outRect.bottom = SizeUtils.dp2px(10);
                } else {
                    outRect.bottom = 0;
                }

                if (position == 0) {
                    outRect.top = dp67;

                } else {
                    outRect.top = 0;
                }

            }
        });

        recyclerView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (dp67 > event.getY()) {

                    int actionMasked = event.getActionMasked();
                    if (actionMasked == MotionEvent.ACTION_DOWN) {
                        headLayoutContent.pressPoint(event.getX(), event.getY());
                    } else if (actionMasked == MotionEvent.ACTION_UP) {
                        headLayoutContent.clickPoint(event.getX(), event.getY());
                    } else {
                        headLayoutContent.resetPress();
                    }

                } else {
                    headLayoutContent.resetPress();
                }

                return false;
            }
        });

        headLayoutContent.setModifyClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //mPresenter.getUserCarInfo();

                Intent intent = ChooseCarActivity.Companion.getStartIntent(QueryResultActivity.this, null);

                startActivityForResult(intent, REQ_CHOOSE_CAR);

            }
        });

        try {
            mPresenter.onCreate(getIntent());
        } catch (Throwable e) {
            e.printStackTrace();
            finish();
        }


        registerEvent(InternalMsgCode.CODE_PAY_SUCCESS, new Function1<Object, Unit>() {
            @Override
            public Unit invoke(Object o) {
                mPresenter.reload();
                return null;
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == REQ_CHOOSE_CAR) {
                //车辆选择
                CarTypeData carTypeData = data.getParcelableExtra(Constants.EXTRA_DATA_CHOOSE_CAR);
                if (carTypeData != null) {
                    //更新车辆信息
                    UserCarInfo userCarInfo = mPresenter.getUserCarInfo();
                    if (userCarInfo != null) {
                        QueryResultPresenter.updateCar(userCarInfo, carTypeData);
                    }

                }

            }
        }

    }

//  @Override
//  protected int getRootLayoutViewId() {
//    return R.id.layout_root;
//  }
//
//  @Override
//  protected int getLoadingFrameId() {
//    return R.id.layout_content;
//  }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
    }

    private void initClick() {
        View.OnClickListener onHeadClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtils.isFastClick()) {
                    return;
                }
                onHeadClick(v);
            }
        };

        findViewById(R.id.img_back).setOnClickListener(onHeadClickListener);
        findViewById(R.id.btn_edit).setOnClickListener(onHeadClickListener);
        findViewById(R.id.tv_goto_fkdj).setOnClickListener(onHeadClickListener);


        View.OnClickListener onHelpPayClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                onHelpPay(v);
            }
        };

        findViewById(R.id.tv_help_pay).setOnClickListener(onHelpPayClickListener);
    }


    private void onHeadClick(View view) {
        int id = view.getId();
        if (id == R.id.img_back) {
            finish();
        } else if (id == R.id.btn_edit) {
            UserCarInfo userCarInfo = null;
            if (mPresenter != null && (userCarInfo = mPresenter.getUserCarInfo()) != null) {
//        AddEditLicenseActivity.startEdit(this,userCarInfo);

                AddCarInfoActivity.Companion.edit(this, userCarInfo);

                finish();
            }
        } else if (id == R.id.tv_goto_fkdj) {
            RouterUtils.start(this, RPaths.fkdj);

        }
    }


    private void onHelpPay(View view) {
        UserCarInfo userCarInfo;
        if (mPresenter != null && (userCarInfo = mPresenter.getUserCarInfo()) != null) {

            Intent intent = RouterUtils.getTargetIntent(this, RPaths.wzdbChooseCar);
            if (intent != null) {
                intent.putExtra(Constants.EXTRA_DATA, userCarInfo);
                startActivity(intent);
            }
        }

    }


    @Override
    public void showCarInfo(UserCarInfo carInfo, boolean fromCache) {
        //showData();
        if (fromCache) {
            //smartRefreshLayout.autoRefresh();
            smartRefreshLayout.autoRefresh(0);
        } else {
            smartRefreshLayout.finishRefresh(2000);
        }
        queryLoadingHeader.setLastRefreshTime(getString(R.string.last_refresh_time, StringUtils.formatTime(carInfo.lastDate * 1000)));

        layoutDataSuccess.setVisibility(View.VISIBLE);
        layoutEmptyOrError.setVisibility(View.GONE);

        headLayoutContent.setCarInfo(carInfo);

        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText(carInfo.carNo);
    }

    @Override
    public void showTips(boolean isSuccess, CharSequence msg) {
        ResultTips.INSTANCE.reset();
        ResultTips.INSTANCE.show(vgRootContent, isSuccess, msg);

    }

    @Override
    public void showFines(UserCarInfo userCarInfo, List<TrafficViolationInfo> list, QueryResult queryResult) {
        //showData();
        layoutDataSuccess.setVisibility(View.VISIBLE);
        customerImg.setVisibility(View.VISIBLE);
        layoutEmptyOrError.setVisibility(View.GONE);

        //查询成功有违章

        int count = 0, points = 0, fee = 0;
        int maxDays = 0;
        for (TrafficViolationInfo violationInfo : list) {
            if ("10".equals(violationInfo.statusName)) {
                count++;

                points += violationInfo.fineDeductPoints;
                fee += violationInfo.getFeeValue();

                int d = violationInfo.getFineOverdueDays();
                if (d > maxDays) {
                    maxDays = d;
                }

            }
        }

        showFineHint(count, points, fee);
        //查询缓存 不可代办
        if (queryResult.fromCache) {
            btnHelpPayment.setEnabled(false);
        }

        QueryResultAdapter adapter = new QueryResultAdapter();

        adapter.setItems(list);
        adapter.setFineInfo(userCarInfo, queryResult.showTips);

        recyclerView.setAdapter(adapter);
        StatTools.sendShow(this, StatisticsId.resultQueryFill);

        //显示违章提示，大于30天的
        if (!queryResult.fromCache && maxDays >= 30) {
            String key = "q_r_tips_last_" + userCarInfo.id;
            boolean hasShowTips = SPUtils.getInstance().getBoolean(key);

            //只显示一次
            if (!hasShowTips) {
                SPUtils.getInstance().put(key, true);


                UiUtils.INSTANCE.addOnGlobalLayoutListener(btnHelpPayment, new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        showExpiredTips();
                    }
                });

            }

        }

    }

    private void showExpiredTips() {
        final ViewGroup viewGroup = findViewById(R.id.layout_root);

        View viewById = viewGroup.findViewById(R.id.layout_bottom);
        if (viewById != null) {
            viewGroup.removeViewInLayout(viewById);
        }

        final NewbieGuideLayout guideLayout = new NewbieGuideLayout(this);
        guideLayout.setId(R.id.layout_bottom);

        viewGroup.addView(guideLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        int[] point = new int[2];
        btnHelpPayment.getLocationOnScreen(point);

        RectF rect = new RectF();

        rect.top = point[1];
        rect.left = point[0];

        rect.right = rect.left + btnHelpPayment.getWidth();
        rect.bottom = rect.top + btnHelpPayment.getHeight();

        rect.top -= SizeUtils.dp2px(15);


        List<NewbieGuideLayout.GuideItem> items = new ArrayList<>();
        items.add(new NewbieGuideLayout.GuideItem(rect,
                R.drawable.guide_car_2,
                "交通违法不及时处理，可能存在扣车风险",
                NewbieGuideLayout.GuideItem.Companion.getNONE(),
                Color.parseColor("#6150FF"),
                Color.parseColor("#5786FF")
        ));
        guideLayout.setGuideItem(items, Color.TRANSPARENT);

        guideLayout.setStepEndCallback(new Function1<View, Unit>() {
            @Override
            public Unit invoke(View view) {

                viewGroup.removeViewInLayout(view);

                return null;
            }
        });

    }


    @Override
    public void showAD(AdModel adModel) {
        if (layoutDataSuccess.isShown() && recyclerView.isShown()) {
            //成功，有结果
            Adapter adapter = recyclerView.getAdapter();
            if (adapter instanceof QueryResultAdapter) {

                ((QueryResultAdapter) adapter).setAdModel(adModel);

                adapter.notifyItemInserted(adapter.getItemCount() - 1);
            }

        } else {
            //无结果
            ResultAdView.load(llSuccessAD, adModel);

        }
    }

    @Override
    public void updateExtendInfo(UserCarInfo userCarInfo) {
        headLayoutContent.setCarInfo(userCarInfo);
    }

    @Override
    public void showEmptySuccess(final UserCarInfo userCarInfo, boolean fromCache) {
        layoutDataSuccess.setVisibility(View.VISIBLE);
        headLayoutContent.setCarInfo(userCarInfo);
        nestedScrollView.setVisibility(View.GONE);
        layoutEmptyOrError.setVisibility(View.VISIBLE);
        customerImg.setVisibility(View.GONE);

        LayoutParams layoutParams = imgIcon.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.width = SizeUtils.dp2px(140);
            layoutParams.height = SizeUtils.dp2px(90);
            imgIcon.setLayoutParams(layoutParams);
        }
        imgIcon.setActualImageResource(R.drawable.mycar_default);

        tvMsgTitle.setText("您的爱车没有违章！继续保持哦~");

        tvMsgContent.setVisibility(View.GONE);

        btnBack.setBackgroundResource(R.drawable.common_btn_white_background_16dp);
        btnBack.setPadding(SizeUtils.dp2px(16), 0, SizeUtils.dp2px(16), 0);
        btnBack.setCompoundDrawablePadding(SizeUtils.dp2px(4));
        btnBack.setTextColor(ContextCompat.getColor(this, R.color.textColorPrimary_70));
        btnBack.setCompoundDrawablesWithIntrinsicBounds(R.drawable.btn_chufajuedingshu, 0, 0, 0);
        btnBack.setText("我有处罚决定书");


        btnNext.setBackgroundResource(R.drawable.common_btn_white_background_16dp);
        btnNext.setPadding(SizeUtils.dp2px(16), 0, SizeUtils.dp2px(16), 0);
        btnNext.setCompoundDrawablePadding(SizeUtils.dp2px(4));
        btnNext.setTextColor(ContextCompat.getColor(this, R.color.textColorPrimary_70));
        btnNext.setCompoundDrawablesWithIntrinsicBounds(R.drawable.btn_chulichenggong, 0, 0, 0);
        btnNext.setText("已处理违章");


        showFineHint(0, 0, 0);

        StatTools.sendShow(this, StatisticsId.resultQueryEmpty);

        btnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtils.isFastClick()) {
                    return;
                }

                RouterUtils.start(v.getContext(), RPaths.fkdj);
            }
        });
        btnNext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //已处理违章
                if (ClickUtils.isFastClick()) {
                    return;
                }
                Intent targetIntent = RouterUtils.getTargetIntent(v.getContext(), RPaths.HISTORY_FINE);
                if (targetIntent != null) {
                    targetIntent.putExtra(Constants.EXTRA_DATA, userCarInfo);
                    startActivity(targetIntent);
                }

            }
        });

//    if(!fromCache){
//      tvHint.postDelayed(new Runnable() {
//        @Override
//        public void run() {
//          if (!isFinishing()){
//            ResultNewsActivity.Companion.startCarResult(QueryResultActivity.this,userCarInfo);
//            overridePendingTransition(R.anim.anim_bottom_open,R.anim.anim_no);
//          }
//
//        }
//      },1500);
//    }


    }


    @Override
    public void showError(UserCarInfo userCarInfo, String msg) {
        //showData();
        if (userCarInfo != null) {
            layoutDataSuccess.setVisibility(View.VISIBLE);
            headLayoutContent.setCarInfo(userCarInfo);
            //findViewById(R.id.ll_btns).setVisibility(View.GONE);
            nestedScrollView.setVisibility(View.GONE);
        } else {
            layoutDataSuccess.setVisibility(View.GONE);
        }
        smartRefreshLayout.finishRefresh();
        customerImg.setVisibility(View.GONE);
        layoutEmptyOrError.setVisibility(View.VISIBLE);
        tvMsgTitle.setText("查询失败");
        tvMsgContent.setVisibility(View.VISIBLE);
        tvMsgContent.setText(msg);

        LayoutParams layoutParams = imgIcon.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.width = SizeUtils.dp2px(64);
            layoutParams.height = SizeUtils.dp2px(64);
            imgIcon.setLayoutParams(layoutParams);
        }

        imgIcon.setImageResource(R.drawable.big_warning);

        btnBack.setBackgroundResource(R.drawable.common_btn_white_background_16dp);
        btnBack.setPadding(0, 0, 0, 0);
        btnBack.setCompoundDrawablePadding(0);
        btnBack.setTextColor(ContextCompat.getColor(this, R.color.textColorPrimary));
        btnBack.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        btnBack.setText("返回");


        btnNext.setBackgroundResource(R.drawable.selector_bg_16dp);
        btnNext.setPadding(0, 0, 0, 0);
        btnNext.setCompoundDrawablePadding(0);
        btnNext.setTextColor(ContextCompat.getColor(this, R.color.white));
        btnNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        btnNext.setText("修改信息");

        showFineHint(0, 0, 0);

        btnBack.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnNext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if (ClickUtils.isFastClick()) {
                    return;
                }

                if (!isFinishing() && mPresenter != null && mPresenter.getUserCarInfo() != null) {
                    AddCarInfoActivity.Companion.edit(QueryResultActivity.this, mPresenter.getUserCarInfo());

                    finish();
                }
            }
        });
        StatTools.sendShow(this, StatisticsId.resultQueryError, msg);

    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        mPresenter.reload();
    }


    private void showFineHint(int count, int points, int fee) {

        if (count > 0) {

            btnHelpPayment.setEnabled(true);
        } else {
            points = 0;
            fee = 0;

            btnHelpPayment.setEnabled(false);
        }

        int color = ContextCompat.getColor(this, R.color.textColorPrimary_70);

        SpannableStringBuilder sb = new SpannableStringBuilder();

        SpannableString num = new SpannableString("可代办");
        num.setSpan(new VerticalCenterSpan(12f, color), 0, num.length(),
                SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(num);
        sb.append(" ").append(String.valueOf(count));
        sb.append("    ");

        num = new SpannableString("扣分");
        num.setSpan(new VerticalCenterSpan(12f, color), 0, num.length(),
                SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(num);
        sb.append(" ").append(String.valueOf(points));
        sb.append("    ");

        num = new SpannableString("罚款");
        num.setSpan(new VerticalCenterSpan(12f, color), 0, num.length(),
                SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(num);
        sb.append(" ").append(String.valueOf(fee));

        tvFineHint.setText(sb);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.img_query_result) {  //在线客服
            startActivity(MineActivity.asIntent(v.getContext(), WyServiceFragment.TAG, ""));
        }

    }
}
